package com.example.bbs.tool;

import android.util.Log;

import java.util.function.Consumer;

public class Counter<T> {

    public static final int NOT_START = 0;
    public static final int COUNTING = 1;
    public static final int FINISHED = 2;
    static final String LOG_TAG = Counter.class.getSimpleName();

    int num;
    int state;
    final Consumer<T> callback;

    T record;

    public Counter(int n, Consumer<T> c) {
        callback = c;
        reset(n);
    }

    synchronized public int count() {
        if (state == FINISHED)
            return -1;
        num++;
        state = COUNTING;
        Log.d(LOG_TAG, "num count: " + num);
        return num;
    }

    synchronized public int countDown() {
        if (state == FINISHED)
            return -1;
        num--;
        Log.d(LOG_TAG, "num countDown: " + num);
        if (num == 0) {
            state = FINISHED;
            callback.accept(record);
        }
        return num;
    }

    synchronized public void reset(int n) {
        num = Math.max(n, 0);
        if (num == 0)
            state = NOT_START;
        else
            state = COUNTING;
    }

    public T getRecord() {
        return record;
    }

    public void setRecord(T record) {
        this.record = record;
    }

    public int checkState() {
        return state;
    }
}
